package com.cmh.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.cmh.config.constant.Constant;
import com.cmh.config.swagger.IgnoreLogin;
import com.cmh.config.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 全局拦截器
 *
 * @author chenPC
 */
@Configuration
public class GlobalInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 调用控制层前拦截请求--对token进行判断
     *
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//        对有IgnoreLogin的注解进行直接跳过验证处理
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(IgnoreLogin.class)) {
            IgnoreLogin ignoreLogin = method.getAnnotation(IgnoreLogin.class);
            if (ignoreLogin.value()) {
                return true;
            }
        }
        String token = request.getHeader(Constant.TOKEN_NAME);
        String tokenCheck = (String) redisUtil.get(token);
//        token判断是否为空
        if (StringUtils.isBlank(token)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                JSONObject res = new JSONObject();
                res.put("auth_status", false);
                res.put("error_msg", "您的token为空，请输入非空且正确的token以验证权限");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500, "请求服务器发生错误，请重试...");
                return false;
            }

        }
//        对token的有效性(redis内是否存在token)进行验证
        if (StringUtils.isBlank(tokenCheck)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                JSONObject res = new JSONObject();
                res.put("auth_status", false);
                res.put("error_msg", "您的token无效或已过期，重新登录获取或输入有效token");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500, "请求服务器发生错误，请重试...");
                return false;
            }

        }

        return true;
    }

    /**
     * 视图渲染前，控制器被调用后的处理方式
     *
     * @param request
     * @param response
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println(request.getContextPath());
    }

    /**
     * 请求结束后调用
     *
     * @param request
     * @param response
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        System.out.println(request.getContextPath());
    }

}
